/*
 *
 *  Copyright (c) <2013-2018>, <Huawei Technologies Co., Ltd>
 *  All rights reserved.
 *  Redistribution and use in source and binary forms, with or without modification,
 *  are permitted provided that the following conditions are met:
 *  1. Redistributions of source code must retain the above copyright notice, this list of
 *  conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice, this list
 *  of conditions and the following disclaimer in the documentation and/or other materials
 *  provided with the distribution.
 *  3. Neither the name of the copyright holder nor the names of its contributors may be used
 *  to endorse or promote products derived from this software without specific prior written
 *  permission.
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 *  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 *  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 *  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 *  Notice of Export Control Law
 *  ===============================================
 *  Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 *  include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 *  Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 *  applicable export control laws and regulations.
 *
 */

package com.koushikdutta.ion;

import com.example.ohosasynclibrary.async.util.LogUtil;
import com.example.ohosasynclibrary.async.util.TextUtils;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;

public class ImageUtil {
    private static final String IMAGE_TYPE = "image/*";
    private static final int IO_END_LEN = -1;
    private static final int CACHE_SIZE = 256 * 1024;
    private static final String LABEL = "ImageUtils";

    private ImageUtil() {
    }

    public static String getMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        return fileNameMap.getContentTypeFor(path);
    }


    /**
     * getPixelMapByUri
     *
     * @param uri     uri
     * @param context 上下文
     * @return 返回位图
     */
    public static PixelMap getPixelMapByUri(Context context, String uri) {

        if (TextUtils.isEmpty(uri)) {
            throw new NullPointerException("uri==null");
        }
        ImageSource imageSource = UriUtils.uriToImageSource(context, Uri.parse(uri));

        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = imageSource.getImageInfo().size;
        decodingOpts.desiredRegion = new Rect(0, 0, imageSource.getImageInfo().size.width, imageSource.getImageInfo().size.height);
        decodingOpts.desiredPixelFormat = imageSource.getImageInfo().pixelFormat;

        return imageSource.createPixelmap(decodingOpts);
    }

    /**
     * 把File 转成 PixelMap
     *
     * @param file 文件
     * @return 返回位图
     */
    public static PixelMap getPixelMapByFile(File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        srcOpts.formatHint = IMAGE_TYPE;
        ImageSource imageSource = ImageSource.create(file.getAbsoluteFile(), srcOpts);

        if (imageSource == null) {
            return null;
        }

        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
//        decodingOpts.desiredSize = imageSource.getImageInfo().size;
//        decodingOpts.desiredRegion = new Rect(0, 0, imageSource.getImageInfo().size.width, imageSource.getImageInfo().size.height);
//        decodingOpts.desiredPixelFormat = imageSource.getImageInfo().pixelFormat;

        return imageSource.createPixelmap(decodingOpts);
    }

    /**
     * 从文件读取字节数组
     *
     * @param file 文件
     * @return 返回字节数组
     */
    public static byte[] read(File file) {
        FileInputStream fileInputStream = null;
        byte[] cache = new byte[CACHE_SIZE];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] result = new byte[0];
        int len = IO_END_LEN;
        try {
            fileInputStream = new FileInputStream(file);
            len = fileInputStream.read(cache);
            while (len != IO_END_LEN) {
                baos.write(cache, 0, len);
                len = fileInputStream.read(cache);
            }
            result = baos.toByteArray();
        } catch (IOException e) {
            IonLog.e("read data from file failed");
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }

            } catch (IOException e) {
                IonLog.e("close file input stream failed");
            }
            try {
                baos.close();
            } catch (IOException e) {
//                e.printStackTrace();
                LogUtil.error(FileCacheStore.class.getName(), "file is delete");
            }
        }
        return result;
    }

}
